package cn.takujo.simple.elasticsearch.client.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.elasticsearch.client.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import cn.takujo.simple.elasticsearch.client.EsRest;
import cn.takujo.simple.elasticsearch.client.FullTextSearchRequestBody;
import cn.takujo.simple.elasticsearch.client.HttpEntityToMap;

public class SearchService {

	@SuppressWarnings("unchecked")
	public static List<SearchKeywordTip> tipList(EsRest es, String[] indices, FullTextSearchRequestBody body)
			throws IOException {
		List<SearchKeywordTip> result = new ArrayList<>();
		String dsl = es.fullTextDisMaxQueryDsl(body);
		Response response = es.searchInIndices(indices, dsl);
		HttpEntity entity = response.getEntity();
		Map<String, Object> trans = HttpEntityToMap.trans(entity);
		Map<String, Object> hits = (Map<String, Object>) trans.get("hits");
		List<Map<String, Object>> hitsList = (List<Map<String, Object>>) hits.get("hits");
		for (Map<String, Object> map : hitsList) {
			SearchKeywordTip tip = new SearchKeywordTip();
			tip.setIndex((String) map.get("_index"));
			tip.setId(Integer.parseInt((String) map.get("_id")));
			tip.setData((Map<String, Object>) map.get("_source"));
			Map<String, Object> hil = (Map<String, Object>) map.get("highlight");
			String tag = body.getHighlightPreTag().replace("<", "").replace(">", "");
			String[] highlight = handleHighlight(hil, tag);
			tip.setHighlightField(highlight[0]);
			tip.setHighlightContent(highlight[1]);
			result.add(tip);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	private static String[] handleHighlight(Map<String, Object> map, String tag) {
		Set<String> keySet = map.keySet();
		int max = 0;
		String hit = null;
		String htm = null;
		for (String key : keySet) {
			List<String> hi = (List<String>) map.get(key);
			String string = hi.get(0);
			Document parse = Jsoup.parse(string);
			Elements select = parse.select(tag);
			int size = select.size();
			if (size > max) {
				max = size;
				hit = key;
				htm = string;
			}
		}
		return new String[] { hit, htm };
	}

}
